package com.example.boot.security;

/**
 * TODO
 *
 * @author ding
 * @since 2024/7/24
 */

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义认证失败处理器
 */
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        // 设置响应字符集
        httpServletResponse.setContentType("text/html;charset=utf8");
        httpServletResponse.setCharacterEncoding("utf-8");
        // 将错误信息告诉前端
        httpServletResponse.getWriter().print(e.getMessage());
        httpServletResponse.getWriter().flush();
        httpServletResponse.getWriter().close();
    }
}
